package cn.laixueit.controller;

import cn.laixueit.commons.CookieUtils;
import cn.laixueit.commons.JwtUtils;
import cn.laixueit.commons.UserInfo;
import cn.laixueit.properties.JwtProperties;
import cn.laixueit.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class AuthController {

    @Autowired
    private AuthService authService;
    @Autowired
    private JwtProperties jwtProperties;


    @PostMapping("/login")
    public ResponseEntity<Void> login(@RequestParam("username")String username,
                                      @RequestParam("password")String password,
                                      HttpServletRequest request, HttpServletResponse response){
        String token = authService.login(username, password);
        if(StringUtils.isNotBlank(token)){
            //正常，写入cookie
            CookieUtils.setCookie(request,response,jwtProperties.getTokenName(),token,jwtProperties.getExpire(),"UTF-8",true);
            return ResponseEntity.status(HttpStatus.OK).build();
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    @GetMapping("/gettoken")
    public ResponseEntity<String> gettoken(HttpServletRequest request){
        String leyouToken = CookieUtils.getCookieValue(request, jwtProperties.getTokenName());
        return ResponseEntity.ok(leyouToken);
    }

    @GetMapping("/logout")
    public ResponseEntity<Void> logout(HttpServletResponse response){
        Cookie cookie = new Cookie(jwtProperties.getTokenName(), null);
        response.addCookie(cookie);
        return ResponseEntity.status(200).build();
    }

    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("leyouToken")String token,
                                           HttpServletRequest request, HttpServletResponse response){
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            // 解析token，刷新token
            String newToken = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            CookieUtils.setCookie(request,response,jwtProperties.getTokenName(),newToken,jwtProperties.getExpire(),"utf-8",true);
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            throw new RuntimeException("获取用户数据失败");
        }
    }

}
